package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fdsendjob.FdSendJobQuery;
import com.uzai.console.dto.fd.fdsendjobdetail.*;
import com.uzai.console.dto.feign.fdSendJob.FdSendJobIdFeignDto;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.FdSendJob;
import com.uzai.console.entity.es.EsFdGroupSendMsg;
import com.uzai.console.entity.es.EsGroupSendMsg;
import com.uzai.console.mapper.FdSendJobMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdSendJobDetailService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.vo.fd.fdsendjob.FdSendJobSubVo;
import com.uzai.console.vo.fd.fdsendjob.FdSendMsgVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 群发任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdSendJobDetailServiceImpl implements FdSendJobDetailService {

    Logger logger = LoggerFactory.getLogger(FdSendJobDetailServiceImpl.class);

    @Autowired
    private FdSendJobMapper fdSendJobMapper;

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MerchantService merchantService;


    /**
     * 查询群发子任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubQuery
     * @return null
     */
    public Page<FdSendJobSubVo> findFdSendJobSubList(FdSendJobSubQuery fdSendJobSubQuery){

        if(fdSendJobSubQuery.getParentId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主任务id");
        }

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<FdSendJobSubVo> fdSendJobSubVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdSendJob> page = new Page<>();
        fdSendJobSubQuery.convert(page);

        FdSendJobQuery fdSendJobQuery = new FdSendJobQuery();
        BeanUtils.copyProperties(fdSendJobSubQuery, fdSendJobQuery);
        fdSendJobQuery.setMerId(fdSendJobSubQuery.getMerId());
        fdSendJobQuery.setParentId(fdSendJobSubQuery.getParentId());
        List<FdSendJob> fdSendJobList = fdSendJobMapper.findByList(page, fdSendJobQuery);
        if(fdSendJobList != null){
            for (FdSendJob fdSendJob : fdSendJobList){
                FdSendJobSubVo fdSendJobSubVo = new FdSendJobSubVo();
                BeanUtils.copyProperties(fdSendJob, fdSendJobSubVo);

                //如果完成发送总数大于预计发送总数，则预计发送总数显示为完成发送总数
                if(Tools.getInteger(fdSendJob.getFinishCount()).intValue() >= Tools.getInteger(fdSendJob.getTotalCount()).intValue()){
                    fdSendJobSubVo.setTotalCount(fdSendJob.getFinishCount());
                }

                //查询群发类型名称
                if(StringUtils.isNotBlank(fdSendJob.getDeviceType())){
                    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(fdSendJob.getDeviceType());
                    if(deviceTypeEnum != null){
                        fdSendJobSubVo.setDeviceTypeName(deviceTypeEnum.getRemark());
                    }
                }

                Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdSendJob.getGroupSendDeviceUniqueId(), null, fdSendJob.getMerId());
                if(device != null){
                    fdSendJobSubVo.setGroupSendDeviceUniqueId(fdSendJob.getGroupSendDeviceUniqueId());
                    fdSendJobSubVo.setGroupSendDeviceId(device.getDeviceId());
                    fdSendJobSubVo.setGroupSendDeviceName(device.getDeviceName());
                    fdSendJobSubVo.setGroupSendDeviceRemark(device.getDeviceRemark());
                }
                fdSendJobSubVoList.add(fdSendJobSubVo);
            }
        }

        //返回到页面分页对象
        Page<FdSendJobSubVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdSendJobSubVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询群发子任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubIdDto
     * @return null
     */
    public FdSendJobSubVo findFdSendJobSub(FdSendJobSubIdDto fdSendJobSubIdDto){
        //返回到页面的VO对象
        FdSendJobSubVo fdSendJobSubVo = new FdSendJobSubVo();

        if(fdSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobSubIdDto.getId(), fdSendJobSubIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(fdSendJob, fdSendJobSubVo);

        //查询群发类型名称
        if(StringUtils.isNotBlank(fdSendJob.getDeviceType())){
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(fdSendJob.getDeviceType());
            if(deviceTypeEnum != null){
                fdSendJobSubVo.setDeviceTypeName(deviceTypeEnum.getRemark());
            }
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdSendJob.getGroupSendDeviceUniqueId(), null, fdSendJob.getMerId());
        if(device != null){
            fdSendJobSubVo.setGroupSendDeviceUniqueId(fdSendJob.getGroupSendDeviceUniqueId());
            fdSendJobSubVo.setGroupSendDeviceId(device.getDeviceId());
            fdSendJobSubVo.setGroupSendDeviceName(device.getDeviceName());
            fdSendJobSubVo.setGroupSendDeviceRemark(device.getDeviceRemark());
        }
        return  fdSendJobSubVo;
    }

    /**
     * 修改群发子任务开始时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubDto
     * @return null
     */
    @Transactional
    public void updateFdSendJobSub(FdSendJobSubDto fdSendJobSubDto){
        if(fdSendJobSubDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入子任务id");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobSubDto.getId(), fdSendJobSubDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() == GroupSendStatusEnum.FINISH.getValue().intValue()
                || fdSendJob.getStatus().intValue() == GroupSendStatusEnum.INVALID.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已完成或者过期的任务不能修改");
        }
        Integer now = DateUtil.getNowTime();

        //未开始任务可以修改开始时间
        if(fdSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){

            Integer beginTime = fdSendJobSubDto.getBeginTime();
            if(beginTime == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能为空");
            }

            if(beginTime-now < 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于当前时间");
            }

            if(beginTime-fdSendJob.getCreateTime() > 7*24*3600){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间必须在创建时间的7天之内");
            }

            fdSendJob.setBeginTime(beginTime);
            fdSendJob.setSendStartTime(beginTime);
        }
        fdSendJob.setUpdateTime(now);
        //修改子任务
        fdSendJobMapper.updateByIdSelective(fdSendJob);
    }

    /**
     * 开始群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void startFdSendJobSub(FdSendJobSubIdDto fdSendJobSubIdDto){
        if(fdSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobSubIdDto.getId(), fdSendJobSubIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue() && fdSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始或暂停任务才能开启");
        }

        Integer now = DateUtil.getNowTime();

        if(fdSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){ //未开始的任务，将开始时间设置成当前时间
            fdSendJob.setBeginTime(now);
            fdSendJob.setSendStartTime(now);
        }else{ //暂停的任务，延迟5分钟咋发送
            fdSendJob.setBeginTime(now+60*5);
            fdSendJob.setSendStartTime(now+60*5);//延迟5分钟
        }

        fdSendJob.setStatus(GroupSendStatusEnum.RUNNING.getValue().intValue());
        fdSendJob.setUpdateTime(now);
        fdSendJob.setFinishCountSnapshot(fdSendJob.getFinishCount());

        //从ES中获取该子任务的已发送数
        FdSendJobIdFeignDto fdSendJobIdFeignDto = new FdSendJobIdFeignDto();
        fdSendJobIdFeignDto.setId(fdSendJob.getId());
        UzaiRespVo<Integer> uzaiRespVo = uzaiBroadcastFeignService.fdSendFinishCount(fdSendJobIdFeignDto);
        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            if(Tools.getInteger(uzaiRespVo.getData()).intValue() != 0){
                fdSendJob.setFinishCountSnapshot(uzaiRespVo.getData());
            }
        }
        fdSendJobMapper.updateByIdSelective(fdSendJob);
    }

    /**
     * 暂停群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void pauseFdSendJobSub(FdSendJobSubIdDto fdSendJobSubIdDto){
        if(fdSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobSubIdDto.getId(), fdSendJobSubIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中任务才能暂停");
        }

        Integer now = DateUtil.getNowTime();
        fdSendJob.setStatus(GroupSendStatusEnum.PAUSE.getValue().intValue());
        fdSendJob.setUpdateTime(now);
        fdSendJobMapper.updateById(fdSendJob);
    }

    /**
     * 结束群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void finishFdSendJobSub(FdSendJobSubIdDto fdSendJobSubIdDto){
        if(fdSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobSubIdDto.getId(), fdSendJobSubIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()
                && fdSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中或暂停中的任务才能结束");
        }

        Integer now = DateUtil.getNowTime();
        fdSendJob.setStatus(GroupSendStatusEnum.FINISH.getValue().intValue());
        fdSendJob.setUpdateTime(now);
        fdSendJobMapper.updateById(fdSendJob);

    }

    /**
     * 删除群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void deleteFdSendJobSub(FdSendJobSubIdDto fdSendJobSubIdDto){
        if(fdSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(fdSendJobSubIdDto.getId(), fdSendJobSubIdDto.getMerId());

        if(fdSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //记录该子任务的消息数
        int msgNumSub = fdSendJob.getTotalCount();

        //删除子任务
        fdSendJobMapper.deleteById(fdSendJob.getId(), fdSendJobSubIdDto.getMerId());

        //删除群发任务ES数据
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        deleteByQueryRequest.setQuery(new TermQueryBuilder("childJobId", fdSendJob.getId()));

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendJobSubIdDto.getMerId());
        elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_group_send_msg, deleteByQueryRequest);

        //查询主任务
        FdSendJob fdSendJobParent = fdSendJobMapper.selectById(fdSendJob.getParentId(), fdSendJob.getMerId());
        if(fdSendJobParent != null){
            //查询主任务消息总数
            Integer totalCountParent = Tools.getInteger(fdSendJobParent.getTotalCount());
            totalCountParent = totalCountParent - msgNumSub;
            //修改主任务消息总数
            if(totalCountParent < 0){
                totalCountParent = 0;
            }
            fdSendJobParent.setTotalCount(totalCountParent);
            fdSendJobMapper.updateByIdSelective(fdSendJobParent);
        }
    }

    /**
     * 查询群发消息列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendMsgQuery
     * @return null
     */
    public Page<FdSendMsgVo> findFdSendMsgList(FdSendMsgQuery fdSendMsgQuery){

        if(fdSendMsgQuery.getChildJobId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入子任务id");
        }

        FdSendJob fdSendJob_child = fdSendJobMapper.selectById(fdSendMsgQuery.getChildJobId(), fdSendMsgQuery.getMerId());
        if(fdSendJob_child == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该子任务不存在");
        }

        //子任务发送时间
        int sendStartTime = Tools.getInteger(fdSendJob_child.getSendStartTime());

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<FdSendMsgVo> fdSendMsgVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdSendMsgVo> page = new Page<>();
        fdSendMsgQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", fdSendMsgQuery.getMerId()));

        //子任务id
        if(fdSendMsgQuery.getChildJobId() != null){
            boolQuery.must(QueryBuilders.termQuery("childJobId", fdSendMsgQuery.getChildJobId()));
        }
        searchSourceBuilder.query(boolQuery);
        //排序
        searchSourceBuilder.sort("delay", SortOrder.ASC);

        //查询运营商其他索引分片
        String uzai_fd_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendMsgQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_fd_group_send_msg, searchSourceBuilder, fdSendMsgQuery.getSize(), fdSendMsgQuery.getFromIndex(), null, null, null, fdSendMsgQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                EsFdGroupSendMsg esFdGroupSendMsg  = JSONObject.parseObject(JSONObject.toJSONString(dataMp), EsFdGroupSendMsg.class);
                FdSendMsgVo fdSendMsgVo = new FdSendMsgVo();
                fdSendMsgVo.setGroupSendDeviceUniqueId(esFdGroupSendMsg.getDeviceUniqueId());
                fdSendMsgVo.setGroupSendDeviceId(esFdGroupSendMsg.getDeviceId());
                if(esFdGroupSendMsg != null){
                    BeanUtils.copyProperties(esFdGroupSendMsg, fdSendMsgVo);
                    if(esFdGroupSendMsg.getDeviceUniqueId() != null){
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(esFdGroupSendMsg.getDeviceUniqueId(), DeviceTypeEnum.getById(esFdGroupSendMsg.getDeviceType()).getKey(), esFdGroupSendMsg.getMerId());
                        if(device != null){
                            fdSendMsgVo.setGroupSendDeviceName(device.getDeviceName());
                            fdSendMsgVo.setGroupSendDeviceRemark(device.getDeviceRemark());
                        }
                    }

                    //消息的发送时间=子任务的发送时间+延迟数
                    fdSendMsgVo.setSendTime(sendStartTime + esFdGroupSendMsg.getDelay());

                    try {
                        FdSendMsgVo.Msg msg = JSONObject.parseObject(esFdGroupSendMsg.getMsg(), FdSendMsgVo.Msg.class);
                        fdSendMsgVo.setMsg(msg);
                    }catch (Exception e){

                    }

                    fdSendMsgVoList.add(fdSendMsgVo);
                }
            }
        }
        page.setRecords(fdSendMsgVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 查询群发消息详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendMsgIdDto
     * @return null
     */
    public FdSendMsgVo findFdSendMsg(FdSendMsgIdDto fdSendMsgIdDto){
        //返回到页面的VO对象
        FdSendMsgVo fdSendMsgVo = new FdSendMsgVo();

        if(fdSendMsgIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendMsgIdDto.getMerId());

        Map<String, Object> map = elasticsearchUtilGroupMsg.searchDataById(uzai_group_send_msg, fdSendMsgIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息不存在");
        }

        EsGroupSendMsg esGroupSendMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), EsGroupSendMsg.class);
        if(esGroupSendMsg == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        FdSendJob fdSendJob_child = fdSendJobMapper.selectById(esGroupSendMsg.getChildJobId(), esGroupSendMsg.getMerId());
        if(fdSendJob_child == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该子任务不存在");
        }

        //子任务发送时间
        int sendStartTime = Tools.getInteger(fdSendJob_child.getSendStartTime());

        if(esGroupSendMsg != null){
            BeanUtils.copyProperties(esGroupSendMsg, fdSendMsgVo);

            try {
                FdSendMsgVo.Msg msg = JSONObject.parseObject(esGroupSendMsg.getMsg(), FdSendMsgVo.Msg.class);
                fdSendMsgVo.setMsg(msg);
            }catch (Exception e){

            }

            //消息的发送时间=子任务的发送时间+延迟数
            fdSendMsgVo.setSendTime(sendStartTime + esGroupSendMsg.getDelay());

        }

        return fdSendMsgVo;

    }

    /**
     * 修改群发消息开始时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendMsgUpdateDto
     * @return null
     */
    @Transactional
    public void updateFdSendMsg(FdSendMsgUpdateDto fdSendMsgUpdateDto){
        if(StringUtils.isBlank(fdSendMsgUpdateDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //查询运营商其他索引分片
        String uzai_fd_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendMsgUpdateDto.getMerId());
        Map<String, Object> map = elasticsearchUtilGroupMsg.searchDataById(uzai_fd_group_send_msg, fdSendMsgUpdateDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息不存在");
        }
        EsFdGroupSendMsg esFdGroupSendMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), EsFdGroupSendMsg.class);

        if(esFdGroupSendMsg == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        FdSendJob fdSendJob = fdSendJobMapper.selectById(esFdGroupSendMsg.getChildJobId(), esFdGroupSendMsg.getMerId());

        if(fdSendJob == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息所在任务不存在");
        }

        if(fdSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue()
            && fdSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()
        ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始或暂停任务才能修改消息发送时间");
        }

        int now = DateUtil.getNowTime();
        //未开始任务可以修改开始时间
        Integer beginTime = fdSendMsgUpdateDto.getBeginTime();
        if(beginTime == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能为空");
        }

        if(beginTime-now < 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于当前时间");
        }

        //计算发送消息延时数
        if(beginTime-fdSendJob.getCreateTime() > 7*24*3600){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间必须在创建时间的7天之内");
        }
        //延迟数=开始时间-子任务发送时间
        int delay = beginTime - fdSendJob.getSendStartTime();
        //修改消息发送时间
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("delay", delay); //延迟数
        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_fd_group_send_msg, fdSendMsgUpdateDto.getId());
    }

    /**
     * 删除群发消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdSendMsgIdDto
     * @return null
     */
    @Transactional
    public void deleteFdSendMsg(FdSendMsgIdDto fdSendMsgIdDto){
        if(fdSendMsgIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendMsgIdDto.getMerId());

        Map<String, Object> map = elasticsearchUtilGroupMsg.searchDataById(uzai_group_send_msg, fdSendMsgIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息不存在");
        }

        EsGroupSendMsg esGroupSendMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), EsGroupSendMsg.class);
        if(esGroupSendMsg == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }
        //查询子任务
        FdSendJob fdSendJob_child = fdSendJobMapper.selectById(esGroupSendMsg.getChildJobId(), esGroupSendMsg.getMerId());
        if(fdSendJob_child == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息所在子任务不存在");
        }

        if(fdSendJob_child.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue()
            && fdSendJob_child.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()
        ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始任务或暂停任务才能删除消息");
        }

        //查询主任务
        FdSendJob fdSendJob_parent = fdSendJobMapper.selectById(esGroupSendMsg.getParentJobId(), esGroupSendMsg.getMerId());
        if(fdSendJob_parent == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息所在主任务不存在");
        }
        //删除消息
        elasticsearchUtilGroupMsg.deleteDataById(uzai_group_send_msg, fdSendMsgIdDto.getId());

        //子任务总消息数
        Integer totalCount_child = Tools.getInteger(fdSendJob_child.getTotalCount());
        fdSendJob_child.setTotalCount(totalCount_child - 1);
        fdSendJobMapper.updateByIdSelective(fdSendJob_child);

        //修改主任务消息数
        Integer totalCount_parent = Tools.getInteger(fdSendJob_parent.getTotalCount());
        fdSendJob_parent.setTotalCount(totalCount_parent - 1);
        fdSendJobMapper.updateByIdSelective(fdSendJob_parent);

    }


}
